package com.d3works.apps.purchase.web;

import com.d3works.apps.base.db.Partner;
import com.d3works.apps.purchase.db.repo.PurchaseOrderRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class PartnerPurchaseController {

  private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  public void checkAnyPurchaseOrderAttached(ActionRequest request, ActionResponse response) {
    try {
      Partner partner = request.getContext().asType(Partner.class);
      if (!partner.getIsSupplier()) {
        long purchaseOrderCount =
            Beans.get(PurchaseOrderRepository.class)
                .all()
                .filter("self.supplierPartner = :partner")
                .bind("partner", partner.getId())
                .count();
        if (purchaseOrderCount > 0) {
          response.setValue("supplierCantBeRemoved", true);
        }
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}
